package com.gamerent.controller;

import com.gamerent.common.ResponseResult;
import com.gamerent.dto.UserLoginDTO;
import com.gamerent.dto.UserRegisterDTO;
import com.gamerent.entity.User;
import com.gamerent.service.UserService;
import com.gamerent.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器 - 合并了原来的用户、认证功能
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseResult<Map<String, Object>> register(@Validated @RequestBody UserRegisterDTO registerDTO) {
        try {
            User user = userService.register(registerDTO);

            Map<String, Object> result = new HashMap<>();
            result.put("userId", user.getId());
            result.put("username", user.getUsername());
            result.put("email", user.getEmail());
            result.put("nickname", user.getNickname());
            result.put("createTime", user.getCreateTime());

            return ResponseResult.success("注册成功", result);
        } catch (Exception e) {
            log.error("用户注册失败: {}", e.getMessage());
            return ResponseResult.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseResult<Map<String, Object>> login(@Validated @RequestBody UserLoginDTO loginDTO,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = userService.login(loginDTO);

            // 更新最后登录信息
            Long userId = (Long) result.get("userId");
            String clientIp = getClientIp(request);
            userService.updateLastLogin(userId, clientIp);

            return ResponseResult.success("登录成功", result);
        } catch (Exception e) {
            log.error("用户登录失败: {}", e.getMessage());
            return ResponseResult.error(e.getMessage());
        }
    }

    /**
     * 验证Token
     */
    @PostMapping("/auth/verify")
    public ResponseResult<Map<String, Object>> verifyToken(@RequestBody Map<String, String> request) {
        try {
            String token = request.get("token");
            if (token == null || token.isEmpty()) {
                return ResponseResult.error(400, "Token不能为空");
            }

            boolean isValid = jwtUtil.validateToken(token);
            Map<String, Object> result = new HashMap<>();

            if (isValid) {
                Long userId = jwtUtil.getUserIdFromToken(token);
                String username = jwtUtil.getUsernameFromToken(token);

                result.put("valid", true);
                result.put("userId", userId);
                result.put("username", username);
                result.put("expiresAt", jwtUtil.getExpirationDateFromToken(token));

                return ResponseResult.success("验证成功", result);
            } else {
                result.put("valid", false);
                return ResponseResult.error(401, "Token无效", result);
            }
        } catch (Exception e) {
            log.error("Token验证失败: {}", e.getMessage());
            return ResponseResult.error("Token验证失败");
        }
    }

    /**
     * 刷新Token
     */
    @PostMapping("/auth/refresh")
    public ResponseResult<Map<String, Object>> refreshToken(@RequestBody Map<String, String> request) {
        try {
            String token = request.get("token");
            if (token == null || token.isEmpty()) {
                return ResponseResult.error(400, "Token不能为空");
            }

            // 检查Token是否还有效（可以是过期的，但格式要正确）
            String newToken = jwtUtil.refreshToken(token);

            Map<String, Object> result = new HashMap<>();
            result.put("accessToken", newToken);
            result.put("expiresIn", 86400); // 24小时，单位秒

            return ResponseResult.success("刷新成功", result);
        } catch (Exception e) {
            log.error("Token刷新失败: {}", e.getMessage());
            return ResponseResult.error("Token刷新失败");
        }
    }

    /**
     * 获取Token信息
     */
    @GetMapping("/auth/info")
    public ResponseResult<Map<String, Object>> getTokenInfo(@RequestHeader("Authorization") String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return ResponseResult.error(400, "Authorization头格式错误");
            }

            String token = authHeader.substring(7);

            if (!jwtUtil.validateToken(token)) {
                return ResponseResult.error(401, "Token无效或已过期");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("userId", jwtUtil.getUserIdFromToken(token));
            result.put("username", jwtUtil.getUsernameFromToken(token));
            result.put("expiresAt", jwtUtil.getExpirationDateFromToken(token));
            result.put("isExpired", jwtUtil.isTokenExpired(token));

            return ResponseResult.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取Token信息失败: {}", e.getMessage());
            return ResponseResult.error("获取Token信息失败");
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/profile")
    public ResponseResult<User> getProfile(@RequestHeader("Authorization") String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return ResponseResult.error(400, "Authorization头格式错误");
            }

            String token = authHeader.substring(7);

            if (!jwtUtil.validateToken(token)) {
                return ResponseResult.error(401, "Token无效或已过期");
            }

            Long userId = jwtUtil.getUserIdFromToken(token);
            User user = userService.findById(userId);

            if (user == null) {
                return ResponseResult.error(404, "用户不存在");
            }

            // 隐藏敏感信息
            user.setPassword(null);

            return ResponseResult.success("获取成功", user);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage());
            return ResponseResult.error("获取用户信息失败");
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/profile")
    public ResponseResult<User> updateProfile(@RequestBody User user,
            @RequestHeader("Authorization") String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return ResponseResult.error(400, "Authorization头格式错误");
            }

            String token = authHeader.substring(7);

            if (!jwtUtil.validateToken(token)) {
                return ResponseResult.error(401, "Token无效或已过期");
            }

            Long userId = jwtUtil.getUserIdFromToken(token);
            user.setId(userId); // 确保只能修改自己的信息

            User updatedUser = userService.updateUser(user);

// 隐藏敏感信息
            user.setPassword(null);
// 删除 user.setSalt(null); // 这一行已经删除

            return ResponseResult.success("更新成功", updatedUser);
        } catch (Exception e) {
            log.error("更新用户信息失败: {}", e.getMessage());
            return ResponseResult.error("更新用户信息失败");
        }
    }

    /**
     * 权限检查
     */
    @PostMapping("/auth/permission/check")
    public ResponseResult<Map<String, Object>> checkPermission(@RequestBody Map<String, Object> request) {
        try {
            // 这里简化处理，实际项目中应该查询数据库
            Long userId = Long.valueOf(request.get("userId").toString());
            String resource = (String) request.get("resource");
            String action = (String) request.get("action");

            log.info("检查用户 {} 对资源 {} 的 {} 权限", userId, resource, action);

            // 简单的权限逻辑：所有用户都有基本的READ权限
            boolean hasPermission = "READ".equals(action) || userId.equals(1L); // 用户ID为1的是管理员

            Map<String, Object> result = new HashMap<>();
            result.put("hasPermission", hasPermission);

            return ResponseResult.success("检查完成", result);
        } catch (Exception e) {
            log.error("权限检查失败: {}", e.getMessage());
            return ResponseResult.error("权限检查失败");
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}